import './index.css';
import { useEffect, useState } from 'react';
import { ConfigProvider } from 'antd';
import { useRequest, useTitle } from 'ahooks';
import flvjs from 'flv.js';
import refresh from '@/static/imgs/refresh.png';
import VoiceInput from '@/components/VoiceInput';
import api from '@/api';
import MessageList from '@/components/MessageList';
import mock_logo from '@/static/imgs/szlc.png';
import jf_logo from '@/static/imgs/jfdsj.png';

const ratio = 2160 / 3840;

const h = window.innerHeight;
const w = ratio * h; //  > winW ? winW : ratio * h;

// console.log(ratio * h,winW, 'aaa')

const logow = (w * 355) / 2160;
const logoh = (h * 115) / 3840;

const logobot = -(h * 230) / 3840;

const bottomBlockBot = (h * 600) / 3840;

const textSize = Math.ceil((60 * h) / 3840) + 'px';

// const flvUrl = 'https://live.aidigitalfield.com/live/0702.flv';
const flvUrl = '/live';

function InteractiveDigitalHuman() {
  const [bg, setBg] = useState('');
  const [message, setMessage] = useState([
    {
      type: 'assistant',
      content: '你好，我是可灵,请问有什么可以帮你？',
    },
    // {
    //   type: 'user',
    //   content: '你好',
    // },
    // {
    //   type: 'assistant',
    //   content:
    //     '抱歉，我不明白你的意思。你还有其他问题吗？抱歉，我不明白你的意思。你还有其他问题吗？抱歉，我不明白你的意思。你还有其他问题吗？抱歉，我不明白你的意思。你还有其他问题吗？抱歉，我不明白你的意思。你还有其他问题吗？',
    // },
  ]);

  const jf = window.location.hostname.includes('jflive');
  // const jf = window.location.hostname.includes('local');

  const { loading, run: questionsAndAnswers } = useRequest(api.getFreePersonList, {
    manual: true,
    onSuccess(res) {
      setMessage((prev) => [...prev, { type: 'assistant', content: res?.answer }]);
      scrollToBottom();
    },
  });

  const fetchBgImg = async () => {
    try {
      const res = (await api.getLatestBackground()) as any;
      if (res?.code === 200) {
        const { data } = res;
        setBg(data.url);
      }
    } catch (error) {
      console.log(error, 'errosss');
    }
  };

  const changeBackgroundToVideo = async (val = '') => {
    await api.changeVideoBg({
      bg_img_url: val,
    });
  };

  useEffect(() => {
    fetchBgImg();
  }, []);

  // const

  const scrollToBottom = () => {
    const messageEnd = document.getElementById('messageEnd');
    console.log(messageEnd.scrollHeight);
    setTimeout(() => {
      messageEnd.scrollTo(0, messageEnd.scrollHeight);
    });
  };

  // 是否可以移动
  const [isMoving, setIsMoving] = useState(false);
  const [lastX, setLastX] = useState(0);
  const [lastY, setLastY] = useState(0);
  const [translateX, setTranslateX] = useState(0);
  const [translateY, setTranslateY] = useState(0);
  const [isSel, setIsSel] = useState(true);

  const refreshHandle = () => {
    // TODO: 添加置空逻辑
    window.location.reload();
  };
  const onBgChange = async (e: any) => {
    if (e.target.files) {
      const selectedFile = e.target.files[0];
      const formData = new FormData();
      formData.append('file', selectedFile);
      const res = await api.uploadBackground(formData);
      changeBackgroundToVideo(res.data.url);
      fetchBgImg();
    }
  };

  const onSend = (text: string) => {
    if (!text) {
      return false;
    }
    console.log(text);
    setMessage([...message, { type: 'user', content: text }]);
    scrollToBottom();
    document.getElementById('videoElement').muted = false;
    questionsAndAnswers({ text, speed: 1.0, useCutin: 1, fastAnswer: 1, voiceId: 'presenter_female' });
  };

  useEffect(() => {
    if (flvjs.isSupported()) {
      const videoElement = document.getElementById('videoElement');
      const flvPlayer = flvjs.createPlayer(
        {
          type: 'flv', // 指定视频类型
          isLive: true,
          url: flvUrl, // FLV 文件的 URL
        },
        {
          // enableWorker: true,
          enableStashBuffer: false,
          autoCleanupSourceBuffer: true,
          // autoCleanupMaxBackwardDuration: 60,
          stashInitialSize: 128,
          isLive: true,
        },
      );
      console.log(videoElement);
      if (videoElement) {
        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load();
        flvPlayer.play();
      }
      setInterval(() => {
        if (flvPlayer) {
          const { buffered } = flvPlayer;
          if (buffered.length > 0) {
            const end = buffered.end(0);
            if (end - flvPlayer.currentTime > 0.15) {
              console.log('执行了');
              flvPlayer.currentTime = end - 0.1;
            }
          }
        }
      }, 6 * 10 * 1000);
    }
    return () => {
      if (flvjs.isSupported()) {
        const videoElement = document.getElementById('videoElement');
        if (videoElement) {
          flvPlayer.unload();
          flvPlayer.detachMediaElement();
          flvPlayer.destroy();
          flvPlayer = null;
        }
      }
    };
  }, []);

  useEffect(() => {
    // window.onmousedown = () => mouseDown();
    window.onmouseup = (e) => mouseUp(e);
  }, []);
  // 鼠标按下事件
  const mouseDown = (e) => {
    setIsMoving(true);
  };

  const touchStart = (e) => {
    setIsMoving(true);
  };

  let bottomBlockDom = document.getElementById('bottomBlock');
  let limitTop = bottomBlockDom?.offsetTop;
  let limitBottom = h - (bottomBlockDom?.offsetTop + bottomBlockDom?.offsetHeight + Math.abs(logobot));

  useEffect(() => {
    // 组件初始化可能获取不到？在挂载之后再获取一下元素
    bottomBlockDom = document.getElementById('bottomBlock');
    limitTop = bottomBlockDom?.offsetTop;
    limitBottom = h - (bottomBlockDom?.offsetTop + bottomBlockDom?.offsetHeight + Math.abs(logobot));
  }, []);

  const move = (e) => {
    // e?.stopPropagation?.();
    // e?.preventDefault?.();

    if (lastX && lastY) {
      // 兼容移动端 touch事件
      const dx = (e.clientX || e.touches[0]?.clientX) - lastX;
      const dy = (e.clientY || e.touches[0]?.clientY) - lastY;

      const newY = translateY + dy;
      // 上界限 平移绝对值 >= 元素距离顶部

      if (newY < 0 && Math.abs(newY) >= limitTop) {
        return;
      }

      // 下界限 平移绝对值 >= 屏高 - 绝对值(元素距离顶部 + 元素高 + 元素距离底部)
      if (newY > 0 && newY >= limitBottom) {
        return;
      }

      setTranslateX(translateX + dx);
      setTranslateY(newY);
    }
    setLastX(e.clientX || e.touches[0]?.clientX);
    setLastY(e.clientY || e.touches[0]?.clientY);
  };

  useEffect(() => {
    console.log(translateY, 'translateY');
  }, [translateY]);

  // 鼠标移动事件
  const onMove = (e) => isMoving && isSel && move(e);

  const mouseUp = (e) => {
    if (e != null) {
    }
    setIsMoving(false);
  };
  const style = { backgroundImage: `url(${bg})` };
  const transformStyle = { transform: `translateY(${translateY}px)`, userSelect: 'none' };

  useTitle(jf ? '精分大数据' : '数字力场-实时互动数字人');

  return (
    <ConfigProvider
      theme={{
        components: {
          Button: {
            colorPrimary: '#776ce6',
            colorPrimaryBorderHover: '#776ce6',
            colorPrimaryBgHover: '#776ce6',
            colorPrimaryHover: '#776ce6',
            colorPrimaryTextActive: '#776ce6',
          },
          Input: {
            colorPrimary: '#776ce6',
            colorPrimaryBorderHover: '#776ce6',
            colorPrimaryBgHover: '#776ce6',
            colorPrimaryHover: '#776ce6',
            colorPrimaryTextActive: '#776ce6',
          },
        },
      }}
    >
      <div className="bg" style={style} onMouseMove={(e) => onMove(e)}>
        <div className="upload">
          <input type="file" accept="image/png, image/jpeg" onChange={onBgChange} />
        </div>
        <div className="refresh" onClick={refreshHandle}>
          <img src={refresh} alt="" />
        </div>
        <div className="wrapper_inter">
          <video id="videoElement" width={w} height={h} autoPlay muted />
          {/* <div className="container_inter" style={{ width: w + 'px', height: h + 'px' }} /> */}
          <div
            id="bottomBlock"
            className="bottomBlock"
            style={{ ...transformStyle, ...{ position: 'absolute', bottom: bottomBlockBot + 'px' } }}
          >
            <MessageList layout={{ h, w, textSize }} data={message} />
            <VoiceInput layout={{ h, w, textSize }} loading={loading} onSend={onSend} />

            <div
              id="logo"
              onTouchStart={(e) => {
                setIsSel(true);
                touchStart(e);
              }}
              onTouchEnd={(e) => {
                setIsMoving(false);
              }}
              onMouseDown={(e) => {
                mouseDown(e);
              }}
              onTouchMove={(e) => {
                onMove(e);
              }}
              onClick={(e) => {
                setIsSel(true);
                e.stopPropagation();
              }}
              className="logo_inter"
              style={{
                width: logow + 'px',
                height: logoh + 'px',
                left: '50%',
                marginLeft: -Math.ceil(logow / 2) + 'px',
                bottom: logobot + 'px',
              }}
            >
              {/* <img
                className="logoName"
                draggable={false}
                src={jf ? jf_logo : mock_logo}
                style={{ width: logow + 'px', height: logoh + 'px' }}
                alt=""
              /> */}
            </div>
          </div>
        </div>
      </div>
    </ConfigProvider>
  );
}

export default InteractiveDigitalHuman;
